package com.ddone.code.executor.service;

import com.ddone.code.executor.factory.ExecutorServiceFactory;
import com.ddone.code.executor.pojo.entity.ColumnMetaData;
import com.ddone.code.executor.pojo.entity.DataSourceConfig;
import com.ddone.code.executor.pojo.entity.ExecuteResult;
import com.ddone.code.executor.pojo.enums.ExecutorType;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * @author ddone
 * @date 2024/8/2-21:20
 */
@Service
public class ExecutorClient {

    private final ExecutorServiceFactory executorServiceFactory;

    @Autowired
    public ExecutorClient(ExecutorServiceFactory executorServiceFactory) {
        this.executorServiceFactory = executorServiceFactory;
    }

    public ExecuteResult executeTask(ExecutorType type, String code) {
        ExecutorService executorService = executorServiceFactory.getExecutorService(type);
        System.out.println(executorService);
        if (executorService != null) {
            return executorService.execute(code, type);
        } else {
            throw new IllegalArgumentException("Invalid Executor Type: " + type);
        }
    }

    public List<String> getExecutorSchemaCompletor(DataSourceConfig config) {
        ExecutorType type = config.getExecutorType() == null ? ExecutorType.Mysql : config.getExecutorType();
        ExecutorService executorService = executorServiceFactory.getExecutorService(type);
        if (executorService != null) {
            return executorService.executorSchemaCompleter(config);
        } else {
            throw new IllegalArgumentException("Invalid Executor Type: " + type);
        }
    }

    public List<String> getExecutorTableCompleter(DataSourceConfig dataSourceConfig,String schemaName) {
        ExecutorType type = dataSourceConfig.getExecutorType() == null ? ExecutorType.Mysql :
                dataSourceConfig.getExecutorType();
        ExecutorService executorService = executorServiceFactory.getExecutorService(type);
        if (executorService != null) {
            return executorService.executorTableCompleter(dataSourceConfig,schemaName);
        } else {
            throw new IllegalArgumentException("Invalid Executor Type: " + type);
        }
    }

    public List<ColumnMetaData> getExecutorColumnCompleter(DataSourceConfig dataSourceConfig, String schema, String table) {
        ExecutorType type = dataSourceConfig.getExecutorType() == null ? ExecutorType.Mysql :
                dataSourceConfig.getExecutorType();
        ExecutorService executorService = executorServiceFactory.getExecutorService(type);
        if (executorService != null) {
            return executorService.tableColumnsCompleter(dataSourceConfig,schema,table);
        } else {
            throw new IllegalArgumentException("Invalid Executor Type: " + type);
        }
    }
}